import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ArticleTagEntity } from '../article/entities/article.tag.entity';
import { TagDto } from './dto/tag.dto';
import { UpdateTagDto } from './dto/update.tag.dto';
import { TagEntity } from './entities/tag.entity';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(TagEntity)
    private readonly tagRepository: Repository<TagEntity>,
    @InjectRepository(ArticleTagEntity)
    private readonly articleTagRepository: Repository<ArticleTagEntity>,
  ) {}

  // 获取tag
  async getTag() {
    const tags = await this.tagRepository.find();
    const p_all = tags.map(async (item) => {
      const newItem = Object.assign(
        {
          articleCount: 0,
        },
        item,
      );
      // 获取几个文章在使用该标签
      newItem.articleCount = await this.articleTagRepository.count({
        where: {
          tagId: newItem.id,
        },
      });
      return newItem;
    });
    return Promise.all(p_all);
  }

  // 创建tag
  async createTag(tagDto: TagDto) {
    const count = await this.tagRepository.count({ where: { name: tagDto.name } });
    if (count > 0) {
      return '该标签名字已存在';
    }
    const createTag = await this.tagRepository.create(tagDto);
    return await this.tagRepository.save(createTag);
  }

  // 删除标签
  async deleteTag(id: string) {
    // 判断有木有文章使用了该标签，有的话则不能删除
    const articleCount = await this.articleTagRepository.count({
      where: {
        tagId: id,
      },
    });
    console.log('2022-10-08 10:22:51', articleCount);
    if (articleCount > 0) {
      return '该标签不能删除';
    }
    return await this.tagRepository.softDelete(id);
  }

  // 更新标签
  async updateTag(tagDto: UpdateTagDto) {
    const { affected } = await this.tagRepository.update(tagDto.id, tagDto);
    console.log('2022-10-08 10:49:28', affected);
    if (affected) {
      return '修改成功';
    } else {
      return '修改失败';
    }
  }
}
